<link rel="stylesheet" href="module/dtree/dtree.css"/>
<link rel="stylesheet" href="module/dtree/font/dtreefont.css"/>
<style>
    /** dtree选中颜色重写 */
    .dtree-theme-item-this {
        background-color: #eeeeee !important;
    }

    #entUserTree {
        height: 535px;
        overflow: auto;
    }

    @media screen and (max-width: 750px) {
        #entUserTree {
            height: auto;
        }
    }
</style>

<!-- 关闭Tab时顶部标题 -->
<div class="layui-body-header">
    <span class="layui-body-header-title">企业用户</span>
    <span class="layui-breadcrumb pull-right">
        <a href="#/console/console1">首页</a>
        <a><cite>企业用户</cite></a>
    </span>
</div>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 左树 -->
        <div class="layui-col-sm12 layui-col-md4 layui-col-lg3">
            <div class="layui-card">
                <div class="layui-card-body mini-bar" id="entUserTree">

                </div>
            </div>
        </div>
        <!-- 右表 -->
        <div class="layui-col-sm12 layui-col-md8 layui-col-lg9">
            <div class="layui-card">
                <div class="layui-card-body">
                    <button id="entUser-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加用户
                    </button>
                    <table class="layui-table" id="entUsertable" lay-filter="entUsertable"></table>
                </div>
            </div>
        </div>

    </div>
</div>
<!--添加应用表格-->
<script type="text/html" id="appmodel">
    <table class="layui-table" id="entAddAppTable" lay-filter="entAddAppTable"></table>
</script>
<!--删除应用表格-->
<script type="text/html" id="delappmodel">
    <table class="layui-table" id="entDelAppTable" lay-filter="entDelAppTable"></table>
</script>
<!-- 添加用户表单弹窗 -->
<script type="text/html" id="entUser-model">
    <table class="layui-table" id="entAddUserTable" lay-filter="entAddUserTable"></table>
</script>
<!-- 企业用户表格操作列 -->
<script type="text/html" id="entUser-table-bar">
<!--    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>-->
    <a class="layui-btn layui-btn-xs " lay-event="addApp">授权应用</a>
    <a class="layui-btn layui-btn-xs " lay-event="delApp">删除应用</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'config', 'util', 'dtree', 'admin'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var util = layui.util;
        var dtree = layui.dtree;
        var admin = layui.admin;
        var tableObj = [];
        var apiEnt = "api-sys/api/entUser/";
        var nowEntCode = 0;
        var nowEntId = 0;
        var getEntChildren = function (arr, parent) {
            let children = [];
            arr.forEach(d => {
                if (d.pid === parent.ent_id) {
                    d.id = d.ent_id;
                    d.title = d.name;
                    d.basicData = {'entCode': d.entCode}
                    children.push(getEntChildren(arr, d))
                }
            })
            parent.children = children;
            return parent;
        }

        //获取企业列表
        admin.req('api-sys/api/enterprise/list', {}, function (res) {
            console.log(res)
            var data = res.data;
            if (data) {
                data.forEach(d => {
                    if (d.top_pid === 0) {
                        d.id = d.ent_id;
                        d.title = d.name;
                        d.basicData = {entCode: d.entCode};
                        tableObj.push(getEntChildren(data, d));
                    }
                })
                console.log(tableObj)
                return tableObj;
            }

        })
        // 树形渲染
        setTimeout(function () {
            $('#entUserTree').html('');
            dtree.render({
                elem: '#entUserTree',
                data: tableObj,
            });
        }, 300);

        // 树形点击事件
        dtree.on('node("entUserTree")', function (obj) {
            var data = obj.param;
            console.log(data)
            nowEntCode = data.basicData.entCode;
            nowEntId = data.nodeId;
            var renderTable = function () {
                //获取项目角色列表
                table.render({
                    elem: '#entUsertable',
                    where: {
                        access_token: config.getToken().access_token
                    },
                    // url: config.base_server + apiEnt + 'treeList?entCode=' + nowEntId,
                    // url: config.base_server + apiEnt + 'list?top_pid='+nowEntId+'&entCode='+data.parentId,
                    url: config.base_server + apiEnt + 'list?entCode=' + nowEntCode,
                    page: false,
                    cols: [[
                        {type: 'numbers'},
                        {field: 'username', sort: true, title: '用户名'},
                        {field: 'nickname', sort: true, title: '昵称'},
                        {field: 'entname', sort: true, title: '所属部门'},
                        {align: 'center', toolbar: '#entUser-table-bar', title: '操作', width: 250}
                    ]]
                });

            };

            renderTable();

            // 监听工具条
            table.on('tool(entUsertable)', function (obj) {
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'edit') { // 查看
                    showEditModel(data);
                } else if (layEvent === 'del') { // 删除
                    doDelete(data);
                } else if (layEvent === 'addApp'){//授权应用
                    showAddAppModel(data);
                } else if (layEvent === 'delApp'){//开通管理
                    showDelAppModel(data);
                }
            });

            // 显示添加应用弹窗
            var showAddAppModel = function (data) {
                var open = layer.open({
                    id: 'entAddAppList',
                    type: 1,
                    title: '授权应用',
                    area: '600px',
                    offset: '120px',
                    content: $('#appmodel').html(),
                    success: function () {
                        table.render({
                            elem: '#entAddAppTable',
                            where: {access_token: config.getToken().access_token},
                            url: config.base_server + 'api-sys/api/entUserApp/listAppNotInEntUser?ent_user_id=' + data.user_id+"&ent_id="+nowEntId,
                            cols: [[
                                {type: 'checkbox', fixed: 'left'},
                                {field: 'app_id', sort: true, title: '应用ID', width: 80},
                                {field: 'name', sort: true, title: '应用名称'},
                            ]]
                        });
                    }, btn: ['添加', '关闭'],
                    yes: function (index, layero) {
                        var checkData = table.checkStatus("entAddAppTable");
                        var checkUsers = checkData.data;
                        console.log(checkUsers);
                        if (!checkUsers || checkUsers.length == 0) {
                            layer.msg("至少选一个", {icon: 2, time: 1500});
                            return;
                        }
                        var reqData = [];
                        checkUsers.forEach(function (item, index) {
                            reqData[index] = {ent_user_id: data.user_id, app_id: item.app_id, entCode: nowEntCode};
                        });
                        layer.load(2);
                        admin.req('api-sys/api/entUserApp/addBatch/', JSON.stringify(reqData), function (data) {
                            layer.closeAll('loading');
                            if (data.code == 0) {
                                layer.msg(data.msg, {icon: 1, time: 1000});
                                table.reload('entAppTable');
                            } else {
                                layer.msg(data.msg, {icon: 2, time: 3000});
                            }
                            layer.close(open);
                        }, 'POST');
                    }, btn2: function (index, layero) {
                        layer.close(open);
                    }
                });
            };
            // 显示删除应用弹窗
            var showDelAppModel = function (data) {
                var open = layer.open({
                    id: 'entDelAppList',
                    type: 1,
                    title: '开通管理',
                    area: '600px',
                    offset: '120px',
                    content: $('#delappmodel').html(),
                    success: function () {
                        table.render({
                            elem: '#entDelAppTable',
                            where: {access_token: config.getToken().access_token},
                            url: config.base_server + 'api-sys/api/entUserApp/list?ent_user_id=' + data.user_id +"&entCode="+nowEntCode,
                            cols: [[
                                {type: 'checkbox', fixed: 'left'},
                                {field: 'app_id', sort: true, title: '应用ID', width: 80},
                                {field: 'appname', sort: true, title: '应用名称'},
                            ]]
                        });
                    }, btn: ['删除', '关闭'],
                    yes: function (index, layero) {
                        var checkData = table.checkStatus("entDelAppTable");
                        var checkUsers = checkData.data;
                        console.log(checkUsers);
                        if (!checkUsers || checkUsers.length == 0) {
                            layer.msg("至少选一个", {icon: 2, time: 1500});
                            return;
                        }
                        var reqData = [];
                        checkUsers.forEach(function (item, index) {
                            reqData[index] = item.eua_id;
                        });
                        layer.load(2);
                        admin.req('api-sys/api/entUserApp/delBatch/', JSON.stringify(reqData), function (data) {
                            layer.closeAll('loading');
                            if (data.code == 0) {
                                layer.msg(data.msg, {icon: 1, time: 1000});
                                table.reload('entAppTable');
                            } else {
                                layer.msg(data.msg, {icon: 2, time: 3000});
                            }
                            layer.close(open);
                        }, 'DELETE');
                    }, btn2: function (index, layero) {
                        layer.close(open);
                    }
                });
            };

            // 删除
            var doDelete = function (obj) {
                layer.confirm('确定要删除吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    console.log(obj)
                    admin.req(apiEnt + 'delBatch?ids='+ obj.eu_id , {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 1000});
                            table.reload('entUsertable');
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 3000});
                        }
                    }, 'DELETE');
                });
            };

            // 添加用户按钮
            $('#entUser-btn-add').click(function () {
                var open = layer.open({
                    id: 'entUserList',
                    type: 1,
                    title: '企业添加用户',
                    area: '600px',
                    offset: '120px',
                    content: $('#entUser-model').html(),
                    success: function () {
                        table.render({
                            elem: '#entAddUserTable',
                            page: true,
                            where: {access_token: config.getToken().access_token},
                            url: config.base_server + 'api-sys/api/entUser/NotInEntList?entId=' + nowEntId,
                            cols: [[
                                {type: 'checkbox', fixed: 'left'},
                                {field: 'user_id', sort: true, title: '用户ID', width: 80},
                                {field: 'nickname', sort: true, title: '昵称'}
                            ]]
                        });
                    }, btn: ['添加', '关闭'],
                    yes: function (index, layero) {
                        var checkData = table.checkStatus("entAddUserTable");
                        var checkUsers = checkData.data;
                        console.log(checkUsers);
                        if (!checkUsers || checkUsers.length == 0) {
                            layer.msg("至少选一个", {icon: 2, time: 1500});
                            return;
                        }
                        var reqData = [];
                        checkUsers.forEach(function (item, index) {
                            reqData[index] = {user_id: item.user_id, ent_id: nowEntId, entCode: nowEntCode};
                        });
                        layer.load(2);
                        admin.req('api-sys/api/entUser/addBatch/', JSON.stringify(reqData), function (data) {
                            layer.closeAll('loading');
                            if (data.code == 0) {
                                layer.msg(data.msg, {icon: 1, time: 1000});
                                table.reload('entUsertable');
                            } else {
                                layer.msg(data.msg, {icon: 2, time: 3000});
                            }
                            layer.close(open);
                        }, 'POST');
                    }, btn2: function (index, layero) {
                        layer.close(open);
                    }
                });
            });



        });

    });
</script>